package com.ts.proj.json;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import com.ts.base.controller.BaseController;
import com.ts.common.constant.InsUpdDelFlagConstant;
import com.ts.proj.entity.*;
import com.ts.proj.service.*;
import com.ts.common.constant.ConsoleConstant;
import com.ts.util.PageData;
import com.ts.util.StringsUtil;
import com.ts.util.DateUtil;
import com.ts.util.EntityAttributeUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import java.util.*;
import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;
import com.ts.util.*;




import javax.servlet.http.HttpSession;
import com.ts.proj.entity.SystemUserEntity;

import com.ts.common.constant.ConsoleConstant;

//说明 字符串：Errorproject，作为替换字符串 LOWERErrorproject

@RestController
public class ErrorprojectJson extends BaseController{

    @Autowired
    private ErrorprojectService errorprojectService;
	@Autowired
    private SystemFieldService systemFieldService;
	
	  @Autowired
    private SystemColumnService systemColumnService;

	  @Autowired
    private ProjectService projectService;

    @Autowired
    private ErrorprojectDetailService errorprojectDetailService;
    @Autowired
    private FileService fileService;


    @Value("${upload.location-pre}")
    private String locaionPre ;

    @Value("${upload.split}")
    private String split;

    /**
     * 显示list
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "/errorproject-list/{state}/{page}/{size}")
    public Map<String,Object> errorprojectList(@PathVariable("state")String vetoFlag ,@PathVariable("page") Integer page, @PathVariable("size") Integer size){
	
		HttpSession session = this.getRequest().getSession();
        SystemUserEntity user = JsonUtils.jsonToObject(session.getAttribute(ConsoleConstant.SESSIONUSER).toString(),SystemUserEntity.class);
	
        PageData pageData = this.getPageData();


		//异常项目名称
        if(null!=pageData.get("projectName")&&!"".equals(pageData.get("projectName").toString())){
            pageData.put("projectName", pageData.get("projectName").toString());
        }
        if(null!=pageData.get("projectName")&&!"".equals(pageData.get("projectName").toString())){
            pageData.put("projectName", pageData.get("projectName").toString());
        }
        if(null != vetoFlag && !"".equals(vetoFlag)){
            pageData.put("vetoFlag", vetoFlag);
        }
		//用户权限
        if(user.getPowerLevel().equals("0")){
            pageData.put("userId", user.getId());
        }
        pageData.put("belongTo", user.getBelongTo());
		
        long count = errorprojectService.count(pageData);
        List<ErrorprojectEntity> errorprojects = errorprojectService.findAll(pageData,page-1,size);

        List<PageData> pdList = new ArrayList<>();
        for(ErrorprojectEntity entity: errorprojects){
            PageData epPd = new PageData();
            epPd.put("id", entity.getUuid());
            epPd.put("realId",entity.getId());
            epPd.put("projectName", entity.getProjectName());
            epPd.put("errorReason", entity.getErrorReason());
            epPd.put("projectId", entity.getProjectId());
            epPd.put("stage", entity.getState());
            epPd.put("vetoFlag",entity.getVetoFlag());
            ProjectEntity projectEntity = projectService.findById(Integer.valueOf(entity.getProjectId()));
            epPd.put("proId",projectEntity.getProId());
            epPd.put("relation", "parent");
            epPd.put("state","closed");
            pdList.add(epPd);
            PageData temp = new PageData();
            temp.put("proID", entity.getId());
            temp.put("deleteFlag", "N");
            List<ErrorProjectDetailEntity> all = errorprojectDetailService.findAll(temp);
            for(ErrorProjectDetailEntity ede:all){
                PageData sonPd = new PageData();
                sonPd.put("id", ede.getId()+5000);
                sonPd.put("uuid", ede.getId());
                sonPd.put("errorReason", ede.getErrorContent());
                sonPd.put("projectName", ede.getErrorTime());
                sonPd.put("projectId", ede.getFeedBack());
                sonPd.put("relation", "son");
                sonPd.put("_parentId", entity.getUuid());
                pdList.add(sonPd);
            }
        }

        pageData.put("total",count);
        pageData.put("rows", pdList);
        return pageData;
    }

    /**
     * 常量增删改
     * @return
     */
    @RequestMapping(value = "/errorproject-ins-upd-del/{id}")
    public Object logCreateUpdate(@PathVariable("id") String id){ 
	
		ErrorprojectEntity errorproject = errorprojectService.findById(Integer.valueOf(id));
        PageData pageData = this.getPageData();

        List<String> strings = EntityAttributeUtil.entityAttribute(ErrorprojectEntity.class);
		 SystemUserEntity systemUserEntity = JsonUtils.jsonToObject(this.getRequest().getSession().getAttribute(ConsoleConstant.SESSIONUSER).toString(),SystemUserEntity.class);

        for(String attr :strings){
            //字段信息维护
            if(null!=pageData.get(attr)&&!"".equals(pageData.get(attr).toString())){
                //目前只能手动添加，这里添加所需要增加和修改的字段
                try {
                    Method[] methods = ErrorprojectEntity.class.getDeclaredMethods();
                    for(int i=0;i<methods.length;i++){
                        Method method = methods[i];
                        Class<?>[] returnType = method.getParameterTypes();
                        if(method.getName().contains(StringsUtil.upperCase(attr))&&!method.getName().contains("get")){
                            if (returnType[0].getName().equals("java.lang.Integer")){
                                method.invoke(errorproject, Integer.valueOf(pageData.getString(attr)));
                            }
                            else{
                                method.invoke(errorproject, pageData.getString(attr));
                            }
                        }
						if(method.getName().equals("setUserId")){
                            errorproject.setUserId(systemUserEntity.getId());
                        }
                        if(method.getName().equals("setBelongTo")){
                            errorproject.setBelongTo(systemUserEntity.getBelongTo());
                        }
						if(method.getName().equals("setPowerLevel")){
                            errorproject.setPowerLevel(systemUserEntity.getPowerLevel());
                        }

                    }

                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }  catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }	
        errorprojectService.save(errorproject);
        return null;
    }


    @RequestMapping(value = "/error-ins-upd-del")
    public Object errorDetailInsUpdDel(){
        PageData pageData = this.getPageData();
        SystemUserEntity systemUserEntity = JsonUtils.jsonToObject(this.getRequest().getSession().getAttribute(ConsoleConstant.SESSIONUSER).toString(),SystemUserEntity.class);
        if(null!=pageData.get("id")&&!"".equals(pageData.get("id").toString())){
            Integer id = -1;
            //修改
            if(null!=pageData.get("id")&&!"".equals(pageData.get("id").toString())){
                id = Integer.valueOf(pageData.get("id").toString());
            }
            ErrorProjectDetailEntity errorProjectDetailEntity = null;
            errorProjectDetailEntity = errorprojectDetailService.findById(id);

            //删除
            if(null!=pageData.get("deleteflag")&&!"".equals(pageData.get("deleteflag").toString())){

                ErrorprojectEntity errorprojectEntity =
                        errorprojectService.findById(Integer.valueOf(errorProjectDetailEntity.getProID()));
                PageData filePage = new PageData();
                filePage.put("errorDetailId",id);
                filePage.put("deleteFlag",'N');
                List<FileEntity> fileEntityList = fileService.findAll(filePage);
                for (FileEntity fileEntity : fileEntityList) {
                    String path = locaionPre;
                    path += errorprojectEntity.getUuid() + split + fileEntity.getState()
                        + split + fileEntity.getState() + "_" + fileEntity.getProjName();
                    fileEntity.setDeleteFlag("Y");
                    fileService.save(fileEntity);
                    File file = new File(path);
                    file.delete();
                }
                errorProjectDetailEntity.setDeleteFlag(pageData.get("deleteflag").toString());
            }
            if(null!=pageData.get("errorTime")&&!"".equals(pageData.get("errorTime").toString())){
                errorProjectDetailEntity.setErrorTime(pageData.get("errorTime").toString());
            }
            if(null!=pageData.get("errorContent")&&!"".equals(pageData.get("errorContent").toString())){
                errorProjectDetailEntity.setErrorContent(pageData.get("errorContent").toString());
            }
            if(null!=pageData.get("proID")&&!"".equals(pageData.get("proID").toString())){
                errorProjectDetailEntity.setProID(pageData.get("proID").toString());
            }
            if(null!=pageData.get("feedBack")&&!"".equals(pageData.get("feedBack").toString())){
                errorProjectDetailEntity.setFeedBack(pageData.get("feedBack").toString());
            }
            errorProjectDetailEntity.setUserId(systemUserEntity.getId());
            errorProjectDetailEntity.setBelongTo(systemUserEntity.getBelongTo());
            errorprojectDetailService.save(errorProjectDetailEntity);
        }
        return "success";
    }

	@RequestMapping("/errorproject-download/{entity}")
    public void export(HttpServletResponse response,@PathVariable("entity") String entity){
        PageData param = new PageData();
        param.put("deleteFlag", InsUpdDelFlagConstant.DELETE_FLAG_N);
        List<ErrorprojectEntity> entitys = errorprojectService.findAll(param);
		param.put("isExport", "Y");
        param.put("tableName", StringsUtil.upperCase(entity));
        List<SystemFieldEntity> all = systemFieldService.findAll(param);
        List<ExcelExportEntity> columnList = new ArrayList<ExcelExportEntity>();
        List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
        //get all columns
        for(SystemFieldEntity systemFieldEntity : all){
            ExcelExportEntity excelExportEntity = new ExcelExportEntity(systemFieldEntity.getFieldCn(), systemFieldEntity.getFieldEn());
			
			if(EntityUtil.getTypeByFieldName(ErrorprojectEntity.class,systemFieldEntity.getFieldEn()).equals("Integer")){
                excelExportEntity.setType(10);
            }else if(EntityUtil.getTypeByFieldName(ErrorprojectEntity.class,systemFieldEntity.getFieldEn()).equals("String")){
                if(null!=systemFieldEntity.getIsMerge()&&systemFieldEntity.getIsMerge().equals("Y")){
                    excelExportEntity.setMergeVertical(true);
                }
            }		
			
            columnList.add(excelExportEntity);
        }
        //get all data
        for(ErrorprojectEntity te: entitys){
            Map<String, Object> map = new HashMap<>();
            for(SystemFieldEntity systemFieldEntity : all){
                String fieldName = systemFieldEntity.getFieldEn();
                String getFunctionName = "get" + StringsUtil.upperCase(fieldName);
                try {
                    Method method = ErrorprojectEntity.class.getMethod(getFunctionName);
                    Object invoke = method.invoke(te);
                    map.put(fieldName, invoke);
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
            dataList.add(map);
        }
        
		PageData temp = new PageData();
        temp.put("deleteFlag", "N");
        temp.put("className", StringsUtil.upperCase(entity));
        List<SystemColumnEntity> columnEntities = systemColumnService.findAll(temp);
        ExportParams exportParams = null;
        if(1==columnEntities.size()){
            exportParams = new ExportParams(columnEntities.get(0).getExportTitle(), columnEntities.get(0).getExportSheet());
        }else{
            exportParams = new ExportParams("SystemColumnEntity数据表此数据不存在胡搜好请确认此条信息", "SHeet");
        }
		
		
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, columnList, dataList);
        try {
            response.setHeader("Content-Disposition","attachment;filename=" + new String((DateUtil.getID()+".xls").getBytes("UTF-8"), "iso8859-1"));
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            BufferedOutputStream bufferedOutPut = new BufferedOutputStream(response.getOutputStream());
            workbook.write(bufferedOutPut);
            bufferedOutPut.flush();
            bufferedOutPut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
      
    }



    @RequestMapping(value = "/errorproject-set/{vetoFlag}/{id}")
    public void errorProjectSet(@PathVariable("vetoFlag")String vetoFlag,
                                @PathVariable("id") String id){

        PageData pd = this.getPageData();
        ProjectEntity project = projectService.findById(Integer.valueOf(id));
        HttpSession session = this.getRequest().getSession();
        SystemUserEntity user = JsonUtils.jsonToObject(session.getAttribute(ConsoleConstant.SESSIONUSER).toString(),SystemUserEntity.class);

        Integer proState = project.getProState();
        if(proState == 0){
            project.setProRukuFlag(1);
        }else if(proState == 1){
            project.setProLixiangFlag(1);
        }else if(proState == 2){
            project.setProJueceFlag(1);
        }else if(proState == 3){
            project.setProTouziFlag(1);
        }else if(proState == 4){
            project.setProTouhouFlag(1);
        }else if(proState == 5){
            project.setProTuichuFlag(1);
        }
        //-1表示异常项目,7表示否决
        if("N".equals(vetoFlag)){
            project.setProState(-1);
        }else if("Y".equals(vetoFlag)){
            project.setProState(7);
        }

        projectService.save(project);

        ErrorprojectEntity errorprojectEntity = new ErrorprojectEntity();
        errorprojectEntity.setUserId(user.getId());
        errorprojectEntity.setBelongTo(user.getBelongTo());
        errorprojectEntity.setIsPublish("N");
        errorprojectEntity.setErrorReason(pd.getString("reason"));
        errorprojectEntity.setProjectId(id);
        errorprojectEntity.setProjectName(project.getProName());
        errorprojectEntity.setState(pd.getString("state"));
        errorprojectEntity.setUuid(project.getUuid());
        errorprojectEntity.setVetoFlag(vetoFlag);
        errorprojectService.save(errorprojectEntity);
    }
}